package com.akl.ssmspringboot.controller;

import com.akl.ssmspringboot.SsmspringbootApplication;
import com.akl.ssmspringboot.utils.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@ControllerAdvice
@RequestMapping("redis")
public class RedisController {

    public static final Logger log = LoggerFactory.getLogger(SsmspringbootApplication.class);
    @Autowired
    private RedisUtils redisUtils;

    //https://blog.csdn.net/weixin_35889818/article/details/81868242
    @RequestMapping("/{id}")
    public String redisSend(@PathVariable(value = "id") String id) {
        //查询缓存中是否存在
        boolean hasKey = redisUtils.exists(id);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = "ID:" + id + ";日期:" + sdf.format(date);
        if (hasKey) {
            //获取缓存
            Object object = redisUtils.get(id);
            log.info("从缓存获取的数据" + object);
            str = object.toString();
        } else {
            //从数据库中获取信息
            log.info("从数据库中获取数据");
//            str = testService.test();
            //数据插入缓存（set中的参数含义：key值，user对象，缓存存在时间10（long类型），时间单位）
            redisUtils.set(id, str, 10L, TimeUnit.MINUTES);
            log.info("数据插入缓存" + str);
        }
        return "./redisSend";
    }

}
